package com.hylanda.sys.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.hylanda.sys.dao.PermissionRepository;
import com.hylanda.sys.entity.UPermission;
import com.hylanda.sys.model.UPermissionQo;


@Service
public class PermissionService {
    @Autowired
    private PermissionRepository permissionRepository;

    public UPermission findById(Long id) {
        UPermission uPermission = permissionRepository.findOne(id);
        return uPermission;
    }

    public UPermission create(UPermission uPermission) {
        UPermission newUPermission = permissionRepository.save(uPermission);
        return newUPermission;
    }

    public UPermission update(UPermission uPermission) {
        return permissionRepository.save(uPermission);
    }

    public void delete(Long id) {
    	permissionRepository.delete(id);
    }

    public Page<UPermission> findPage(UPermissionQo uPermissionQo){
       Pageable pageable = new PageRequest(uPermissionQo.getPage(), uPermissionQo.getSize(), new Sort(Sort.Direction.ASC, "id"));
       return permissionRepository.findAll(pageable);
    }

	public List<UPermission> findAll() {
		List<UPermission> permissions = permissionRepository.findAll();
        return permissions;
	}

	public UPermission getTree() {
		List<UPermission> list = findAll();
		List<UPermission> rootList = makeTree(list);
		return rootList.get(0);
	}

	private List<UPermission> makeTree(List<UPermission> list) {
		List<UPermission> parent = new ArrayList<UPermission>();
//		for (UPermission e : list) {
//			if (e.getParent() == null) {
//				e.setChildren(new ArrayList<UPermission>(0));
//				parent.add(e);
//			}
//		}
		list.removeAll(parent);
		makeChildren(parent, list);
		return parent;
	}
	
	private void makeChildren(List<UPermission> parent, List<UPermission> children) {
		if (children.isEmpty()) {
			return ;
		}
		List<UPermission> tmp = new ArrayList<UPermission>();
//		for (UPermission c1 : parent) {
//			for (UPermission c2 : children) {
//				c2.setChildren(new ArrayList<UPermission>(0));
//				if (c1.getId().equals(c2.getParent().getId())) {
//					c1.getChildren().add(c2);
//					tmp.add(c2);
//				}
//			}
//		}
		children.removeAll(tmp);
		makeChildren(tmp, children);
	}
	

}
